<template>
    <div class="cntr">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="放箱单号" prop="release_no">
                        <textupperinput
                            v-model.trim="formData.release_no"
                        ></textupperinput>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱号" prop="cntr">
                        <el-input v-model="formData.cntr" disabled></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="4">
                    <el-form-item label="箱况" prop="dam_id">
                        <el-select
                            v-model="formData.dam_id"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrDam"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="尺寸" prop="cntr_siz_cod">
                        <el-select
                            v-model="formData.cntr_siz_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrSiz"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱型" prop="cntr_typ_cod">
                        <el-select
                            v-model="formData.cntr_typ_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrTyp"
                                :key="optValue.value"
                                :label="optValue.value"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="站点" prop="cfs_cod">
                        <el-select
                            v-model="formData.cfs_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cyCfs"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="客户" prop="cntr_corp_cod">
                        <el-select
                            v-model="formData.cntr_corp_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                        >
                            <el-option
                                v-for="optValue in cntrCorp"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="放箱日期" prop="allow_date">
                        <el-date-picker
                            v-model="formData.allow_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="提箱日期" prop="leav_port_tim">
                        <el-date-picker
                            v-model="formData.leav_port_tim"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="提箱车号" prop="out_truck_no_c">
                        <el-input v-model.trim="formData.out_truck_no_c" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="提箱司机电话" prop="out_truck_tel">
                        <el-input v-model.trim="formData.out_truck_tel" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="fee">
        <el-table
            ref="tableRef"
            :data="tableData"
            row-key="id"
            table-layout="auto"
            @row-dblclick="onFeeDbClick"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_unit_cod"
                label="客户"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_unit_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in client"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_unit_cod, client) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_in_out"
                label="收付"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_in_out"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in SelectOptionFeeInOut"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{
                            transFormatter(
                                scope.row.fee_in_out,
                                SelectOptionFeeInOut,
                            )
                        }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_cod"
                label="费目"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in feecod"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_cod, feecod) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="currency_cod"
                label="货币"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.currency_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in currency"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.currency_cod, currency) }}
                    </template>
                </template>
            </el-table-column>

            <el-table-column
                v-bind:align="'center'"
                prop="amount"
                label="金额"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model="scope.row.amount"
                            :min="0"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.amount }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-button
                            size="small"
                            type="primary"
                            @click="onEdit(scope.$index, scope.row)"
                            >确定</el-button
                        >
                        <el-button
                            size="small"
                            type="info"
                            @click="onCancel(scope.$index, scope.row)"
                            >取消</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="onDel(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="btn-group">
        <el-button-group>
            <el-button
                class="btn"
                type="primary"
                v-debounce="save"
                size="large"
            >
                保存
            </el-button>
            <el-button class="btn" type="primary" @click="reset" size="large"
                >重置</el-button
            >
            <!-- <el-button
                class="btn"
                type="primary"
                @click="addDefaultFee"
                size="large"
                >生成默认费用</el-button
            > -->
            <el-button class="btn" type="primary" @click="addFee" size="large"
                >增加费用</el-button
            >
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="GateOut">
import { ref, reactive, onMounted, toValue } from 'vue';
import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';
import type { CntrModel } from '@/common/types/container';
import type { FeedetModel } from '@/common/types/business';
import { Request } from '@/app/request';
import { useAppStore } from '@/store/app';
import { useSysStore } from '@/store/sys';
import { transFormatter } from '@/common/tools';
import { isNil, omit, pick, template } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
import textupperinput from '@/components/forms/TextUpperInput.vue';
const {
    client,
    SelectOptionFeeInOut,
    feecod,
    currency,
    cntrDam,
    cntrSiz,
    cntrTyp,
    cyCfs,
    cntrCorp,
} = useAppStore();

const { oper } = useSysStore();
const formRef = ref<FormInstance>();
const formData = reactive<CntrModel>({});
const tableRef = ref<TableRefs>();
const tableData = reactive<FeedetModel[]>([]);
const props = defineProps<{
    data: CntrModel;
}>();
const emit = defineEmits<{
    update: [action: CntrModel];
    close: [];
}>();
const rules = reactive<FormRules>({
    leav_port_tim: [
        { required: true, message: '请输入离场时间', trigger: 'blur' },
    ],
    release_no: [
        { required: true, message: '请输入放箱单号', trigger: 'blur' },
    ],
    cntr_corp_cod: [{ required: true, message: '请选择客户', trigger: 'blur' }],
});
let temFeedet: any;

const reset = () => {
    formRef.value?.resetFields();
    tableData.length = 0;
};

onMounted(() => {
    reset();
    Object.assign(formData, props.data);
    formData.out_truck_no_c = '鲁B';
});
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );
    if (formValid) {
        for (let index = 0; index < tableData.length; index++) {
            const element = tableData[index];
            if (element.amount! <= 0) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '费用金额不能为0，不能保存',
                });
                return;
            }
            if (element.isEdit) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '存在未保存费用',
                });
                return;
            }
        }

        if (props.data) {
            // 修改
            const param = toValue(formData);
            // param['feedet'] = toValue(tableData);
            const req = new Request(
                '箱离场',
                pick(param, [
                    'id',
                    'release_no',
                    'cntr_corp_cod',
                    'leav_port_tim',
                    'allow_date',
                    'out_truck_no_c',
                    'out_truck_tel',
                    'remark',
                ]),
            );
            const r = await req.post();
            if (r.code > 100) {
                emit('update', r.obj as CntrModel);
                // reset();
                return true;
            }
        }
    } else {
        return false;
    }
};
const addFee = () => {
    tableData.push({
        isEdit: true,
        currency_cod: 'RMB',
    });
    temFeedet = null;
};
//费用删除
const onDel = async (index: number, row: any) => {
    if (props.data) {
        const req = new Request('费用删除', { ids: [row.id] });
        const r = await req.post();
        if (r.code > 100) {
            tableData.splice(index, 1);
        }
    } else {
        tableData.splice(index, 1);
    }
};
//费用表双击
const onFeeDbClick = (row: any) => {
    // console.log(row);
    if (row.isEdit) {
        return;
    }
    temFeedet = {};
    Object.assign(temFeedet, omit(row, ['isEdit']));
    row.isEdit = true;
};
// 费用确定
const onEdit = async (_index: number, row: FeedetModel) => {
    if (props.data) {
        if (row.id) { /* empty */ } else {
            row['cntr_no'] = formData.id;
            row['fee_nam'] = oper.name;
            row['fee_tim'] = formData.to_port_tim;
        }
    }
    row.isEdit = false;
};
// 费用取消修改
const onCancel = (index: number, row: FeedetModel) => {
    if (isNil(temFeedet)) {
        tableData.splice(index, 1);
    } else {
        Object.assign(row, temFeedet);
        row.isEdit = false;
    }
};
</script>
<style lang="scss" scoped>
.cntr {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.fee {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
